package com.xy.yunduo.utils.http;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpUtil {
    private static final Logger log= LoggerFactory.getLogger(HttpUtil.class);

    public static enum Method {
        GET("GET"),
        POST("POST");

        private String label;

        private Method(String label) {
            this.label = label;
        }

        public String getLabel() {
            return label;
        }

        public String getCode() {
            return name();
        }
    }

    private HttpUtil() {

    }

    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;

        HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();

        return httpServletRequest;

    }


    public static String getIpAddr(final HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        System.out.println("****************request ip:" + ip);
        // 如果是多级代理，那么取第一个ip为用户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(0, ip.lastIndexOf(",")).trim();
        }
        return ip;
    }

    public static String getCookie(final HttpServletRequest request, final String paramName, final String headerName) {
        String value = request.getParameter(paramName);
        if (StringUtils.isBlank(value)) {
            Cookie cookie = WebUtil.getCookie(request, paramName);
            if (cookie != null) {
                value = cookie.getValue();
            }
        }
        if (StringUtils.isBlank(value)) {
            value = request.getHeader(headerName);
        }
        return value;
    }

    public static void addCookie(HttpServletResponse response, String name, String value, String path, String domain, int expiry, boolean httpOnly) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(expiry);
        cookie.setPath(path);
        cookie.setDomain(domain);
        cookie.setHttpOnly(httpOnly);
        response.addCookie(cookie);
    }


    public static boolean isWeixinBrowser(final HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        Pattern pattern = Pattern.compile("micromessenger", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(userAgent);
        return matcher.find();
    }

    public static HttpsURLConnection getHttpsURLConnection(String strUrl)
            throws IOException {
        URL url = new URL(strUrl);
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
        return httpsURLConnection;
    }

    public static Map<String, String> getParamsMap(HttpServletRequest request) {
        Map<String, String> paramsMap = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iterator = requestParams.keySet().iterator(); iterator.hasNext(); ) {
            String name = (String) iterator.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            paramsMap.put(name, valueStr);
        }
        return paramsMap;
    }


}
